<?php

namespace Event\Drive\Service;

use Event\Drive\Contracts\ValidatorContract;
use Event\Drive\Exceptions\EventDriveException;
use Particle\Validator\Validator;

abstract class EventBaseValidator implements ValidatorContract
{
    /**
     * @var Validator
     */
    protected $validator;

    private $eventClassName;

    public function __construct(string $eventClassName)
    {
        $this->validator = new Validator();
        $this->eventClassName = $eventClassName;
    }
    abstract public function rule(array $params);

    public function check(array $params) : array
    {
        $this->rule($params);
        $validationResult = $this->validator->validate($params);
        //存在验证异常的处理
        if ($messageArr = $validationResult->getMessages()) {
            $failedArr = [];
            //对存在异常的数据进行处理
            foreach ($messageArr as $message) {
                $failedArr = array_merge($failedArr, $message);
            }
            throw new EventDriveException($this->getEventClassName(),PHP_EOL.implode(PHP_EOL, $failedArr));
        }
        return $validationResult->getValues();
    }

    /**
     * 获取当前处理的事件类名-暂不对外开放
     * @return mixed
     */
    private function getEventClassName()
    {
        return $this->eventClassName;
    }
}
